import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders, HttpEventType } from '@angular/common/http';
import { ToastController, LoadingController } from 'ionic-angular';
import { StorageProvider } from '../storage/storage';
import { App } from 'ionic-angular';  
import { DialogProvider } from '../../providers/dialog/dialog';
/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {

	public APPLE_ID = "kmkl2018";
	public APPLE_KEY = "kmkl1314kmkl1314kmkl1314kmkl1314";

	// public APP_HTTP_URL = 'http://localhost';

	// public APP_IMG = 'http://localhost/cpile/upload';
	//  public APP_IMG = 'http://47.106.156.103/cpile/upload';

	//  public APP_HTTP_URL = 'http://47.106.156.103';
	 public APP_SERVE_URL = '/app';

	public authorization = '';

	 public APP_IMG = 'https://gx.mzzckj.com/cpile/upload';
	 public APP_HTTP_URL = 'https://gx.mzzckj.com';
	//  public APP_HTTP_URL = 'http://localhost';
	//  public APP_IMG = 'http://localhost/cpile/upload';
	 
	 public login_stuta = 0;

	//Observable => subscribe
	constructor(
		public http: HttpClient,
		public toastCtrl: ToastController,
		public loadingCtrl: LoadingController,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		private app:App,) {
		console.log('Hello HttpProvider Provider');
		this.APP_SERVE_URL = this.APP_HTTP_URL + this.APP_SERVE_URL;
	}

	/**
	 * request请求
	 */
	public postJson(modal: any, action: any, data: any, isload: any) {
		//post提交
		return new Promise((success, complete) => {
			let loading = this.loadingCtrl.create({
				content: '正在请求...'
			});
			//请求状态
			if(isload) {
				loading.present();
			}
			//获取数据
			this.postData(modal, action, data).subscribe(res => {
				if(success)
					success(res)
			}, error => {
				if(isload)
					loading.dismiss();
					if (error.status === 401) {
//						this.dialog.showAlert('401', JSON.stringify(this.login_stuta));
						if (this.login_stuta === 1) {
							this.login_stuta = 0;
							this.dialog.showAlert('你的账号已在另一台设备登录。如非本人操作,则密码可能已泄露,建议修改密码!', '');
							this.app.getRootNav().setRoot('LoginPage');
						}
					
				};
				if (error.status === 500) {
					error.error.status === 500;
					success(error.error);
					// this.dialog.showToast('bottom', error.error.message)
					};
			}, () => {
				if(isload)
					loading.dismiss();
				if(complete)
					complete();
			});
		});
	}

	/**
	 * request请求
	 */
	public postFile(modal: any, action: any, data: any, isload: any) {
		//post提交
		return new Promise((success, complete) => {
			let loading = this.loadingCtrl.create({
				content: '正在请求...'
			});
			//请求状态
			if(isload) {
				loading.present();
			}
			//获取数据
				this.postFileData(modal, action, data).subscribe(event => {
					//事件侦听
					if(event.type === HttpEventType.DownloadProgress) {
						// 文件下载进度
						const percentDone = Math.round(100 * event.loaded / event.total);
						console.log(`File is ${percentDone}% uploaded.`);
					} else if(event.type === HttpEventType.UploadProgress) {
						// 文件上传进度
						const percentDone = Math.round(100 * event.loaded / event.total);
						console.log(`File is ${percentDone}% uploaded.`);
					} else if(event instanceof HttpResponse) {
						if(success)
							success(event.body);
					}
				}, error => {
					if(isload)
						loading.dismiss();
						console.log(error);
					this.toastMessage(error.error.message);
				}, () => {
					if(isload)
						loading.dismiss();
					if(complete)
						complete()
				});
		});
	}

	/**
	 * 请求数据(模块,方法,数据,令牌)
	 */
	private postData(modal: any, action: any, data: any) {
		//post提交
		let postUrl = this.APP_SERVE_URL;
		if(modal != "")
		postUrl += '/' + modal;
		if(action != "")
		postUrl += '/' + action;
		let header;
		if (this.authorization === '') {
			header = new HttpHeaders().set('Content-Type', 'application/json;charset=utf-8');
		} else {
			header = new HttpHeaders().set('Content-Type','application/json;charset=utf-8');
			header = new HttpHeaders().set('Authorization', 'Bearer '+this.authorization);
		}
		//发起请求 表单提交
		return this.http.post(postUrl, data, {
			headers: header,
			responseType: 'json'
		});
	}

	/**
	 * 上传文件(模块,方法,数据,令牌)
	 */
	private postFileData(modal: any, action: any, data: any) {
		//post提交
		let postUrl = this.APP_SERVE_URL;
		if(modal != "")
		postUrl += '/' + modal;
		if(action != "")
		postUrl += '/' + action;
		//开始请求
		return this.http.post(postUrl, data, {
			headers: new HttpHeaders().set('Content-Type', 'application/json;charset=utf-8'),
			observe: 'events',
			reportProgress: true,
			responseType: 'json'
		});
	}

	/**
	 * 消息显示
	 */
	private toastMessage(message: any) {
		//请求异常
		this.toastCtrl.create({
			message: message,
			duration: 2000,
			position: 'top'
		}).present();
	}

	public setAuthorization(data) {
		this.authorization = data;
	}

}
